<?php


namespace common\assets;

use Yii;
use yii\helpers\Url;
use yii\helpers\FileHelper;
use yii\web\AssetBundle;

/**
 * description of AppAsset
 *
 * @author FireLoong
 */
class AppAsset extends AssetBundle
{
    const CACHE_BUNDLE_KEY = 'common.appAsset.depends';

    public function init()
    {
        parent::init();
        $this->depends = $this->getDepends();
    }

    /**
     * 视图文件中添加CSS文件
     * @param string|array $cssFile 要添加的CSS文件名
     * @param boolean $isAfter 是否放在 $css 后面
     * @return boolean
     * @throws \yii\base\InvalidConfigException
     */
    public function addCss($cssFile, $isAfter = true)
    {
        if (is_string($cssFile)) {
            $cssFile = array($cssFile);
        }
        if (!is_array($cssFile)) {
            return FALSE;
        }

        if (!is_null($this->sourcePath)) {
            $url = Yii::$app->assetManager->getPublishedUrl($this->sourcePath);
            if (!is_dir($this->basePath . str_replace($this->baseUrl, '', $url))) {
                Yii::$app->assetManager->publish($this->sourcePath);
            }
        }

        $cssFiles = [];
        foreach ($cssFile as $item) {
            $cssFiles[] = Url::isRelative($item) ? FileHelper::normalizePath($url . '/' . ltrim($item, '/')) : $item;
        }

        $bundle = Yii::$app->getAssetManager()->bundles[self::class];

        $bundle->css = $isAfter ? array_merge($bundle->css, $cssFiles) : array_merge($cssFiles, $bundle->css);
    }

    /**
     * 视图文件中添加JS文件
     * @param string|array $jsFile 要添加的JS文件名
     * @param boolean $isAfter 是否放在 $js 后面
     * @return boolean
     * @throws \yii\base\InvalidConfigException
     */
    public function addJs($jsFile, $isAfter = true)
    {
        if (is_string($jsFile)) {
            $jsFile = array($jsFile);
        }
        if (!is_array($jsFile)) {
            return FALSE;
        }
        if (!is_null($this->sourcePath)) {
            $url = Yii::$app->assetManager->getPublishedUrl($this->sourcePath);
            if (!is_dir($this->basePath . str_replace($this->baseUrl, '', $url))) {
                Yii::$app->assetManager->publish($this->sourcePath);
            }
        }

        $jsFiles = [];
        foreach ($jsFile as $item) {
            $jsFiles[] = Url::isRelative($item) ? FileHelper::normalizePath($url . '/' . ltrim($item, '/')) : $item;
        }

        $bundle = Yii::$app->getAssetManager()->bundles[self::class];

        $bundle->js = $isAfter ? array_merge($bundle->js, $jsFiles) : array_merge($jsFiles, $bundle->js);
    }

    public function getDepends()
    {
        return Yii::$app->cache->get(self::CACHE_BUNDLE_KEY) ?: [];
    }

    public function setDepends($depends = [])
    {
        $oldDepends = $this->getDepends();
        Yii::$app->cache->set(self::CACHE_BUNDLE_KEY, array_unique(array_merge($oldDepends, $depends)));
    }
}
